<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/3
 * Time: 10:05
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\common\model\Tag;
use app\common\model\teacher\Teacher;
use app\common\model\teacher\TeacherDegree;
use think\Db;
use think\Exception;
use think\Log;

class Teachers extends AdminController
{
    /**
     * 老师列表
     * @return static
     */
    public function list() {

        $form = $this->getAndCheckForm([
            ['limit', 'require|^\\d+$'],
            ['offset', 'require|^\\d+$'],
        ]);

        $pageResponse = Teacher::manageList($form['limit'], $form['offset'], $form['keywords']??null);

        return $pageResponse;
    }

    /**
     * 保存老师信息
     * @return ApiResponse
     */
    public function save() {

        $data = input('post.');

        /*if (isset($data['id'])) { // 更新
            Db::startTrans();
            try {
                Teacher::where('id', $data['id'])->update($data);
                Db::commit();
                return ApiResponse::success();
            } catch (\Exception $e){
                Db::rollback();
                Log::error($e->getMessage());
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'操作失败');
            }
        } else { // 新增
            if (isset($data['password'])) $data['password'] = Teacher::passwordEncrypt($data['password']);

            if (isset($data['username'])) {
                $teacher = Teacher::get(['username'=>$data['username']]);
                if ($teacher) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'用户名已经存在');
            }

            Db::startTrans();
            try {
                Teacher::create($data);
                Db::commit();
                return ApiResponse::success();
            } catch (\Exception $e) {
                Db::rollback();
                Log::error($e->getMessage());
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'操作失败');
            }

        }*/
        // exit;

        $id = intval($data['id'] ?? 0);
        if (isset($data['password'])) {
            $data['password'] = Teacher::passwordEncrypt($data['password']);
        }

        $model = Teacher::get($id);
        if (is_null($model)) {
            $model = new Teacher();
        }
        if (isset($data['username']) &&
            ((isset($model->username) && $data['username']!=$model->username) || !isset($model->username)) ) {
            if (Teacher::checkUsername($data['username']))
                ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'用户名已经存在');
        }
        $model->data($data);
        $model->save();

        return ApiResponse::success();
    }

    public function set_recommend() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['recommend', 'require|integer',],
        ]);
        Teacher::update([
            'id' => $form['id'],
            'recommend' => empty($form['recommend']) ? 0 : 1,
        ]);
        return ApiResponse::success();
    }

    /**
     * 设置课程隐藏或取消
     * @return ApiResponse
     */
    public function set_hide() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['hide', 'require',],
        ]);

        Teacher::setHide(intval($form['id']), intval($form['hide']));

        return ApiResponse::success($form);
    }

    public function list_names() {
        $list = Teacher::listNames();
        return ApiResponse::success($list);
    }

    /**
     * 列出老师标签
     *
     * @return ApiResponse
     */
    public function tags() {
        $form = $this->getAndCheckForm([
            ['teacher_id', 'integer',],
        ]);

        $teacher_id = intval($form['teacher_id'] ?? 0);
        if ($teacher_id) $list = Tag::getByTeacher($teacher_id);
        else $list = Tag::all();

        return ApiResponse::success($list);
    }

    /**
     * 给老师添加
     *
     * @return ApiResponse
     */
    public function tag_add() {

        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer',],
            ['tag_id', 'integer',],
        ]);

        try{
            Db::startTrans();

            if (empty($form['tag_id']) && empty($form['tag'])) {
                ApiResponse::error(ApiResponse::ERR_FORM_INVALID, '请输入tag或tag_id');
            }

            if (empty($form['tag'])) {
                $tag_id = intval($form['tag_id']);
            } else {
                $data = ['title' => $form['tag']];
                $tag = Tag::get($data);
                if (empty($tag)) {
                    $tag = Tag::create($data);
                }
                $tag_id = $tag->id;
            }
            Tag::addToTeacher($form['teacher_id'], $tag_id);

            Db::commit();
            return ApiResponse::success([
                'id' => $tag_id,
                'title' => $form['tag'] ?? null,
            ]);

        }catch (Exception $ex){
            Db::rollback();
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,$ex->getMessage());
        }
    }

    /**
     * 移除老师的标签
     *
     * @return ApiResponse
     */
    public function tag_remove() {
        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer',],
            ['tag_id', 'require|integer',],
        ]);

        Tag::rmFromTeacher($form['teacher_id'], $form['tag_id']);

        return ApiResponse::success();
    }

    public function degree_list() {
        $list = TeacherDegree::all();
        return ApiResponse::success($list);
    }

    public function degree_save() {
        $form = $this->getAndCheckForm([
            ['name', 'require'],
        ]);

        $id = intval($form['id'] ?? 0);
        if ($id > 0) TeacherDegree::update($form);
        else TeacherDegree::create($form);

        return ['code'=>200];
    }

    public function degree_del() {
        $form = $this->getAndCheckForm([
            ['id', 'require'],
        ]);
        TeacherDegree::destroy(intval($form['id']));
        return ['code'=>200];
    }

    /**
     * 提供老师登录聊天室
     * 
     * @return array
     */
    public function chat_login() {
        $name = input('post.name');
        $teacher = Db::table('teacher')->where('name', '=', $name)->find();
        if (empty($teacher)) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'教师不存在');
        }
        $chat = Teacher::chatToken($teacher);
        return ['code'=>200, 'chat' => $chat];
    }

}